<?php
/**
 * @link      http://www.imtfy.com
 * @copyright Copyright (c) 2010-2020 phpWit.
 * @license   http://www.imtfy.com/license
 * @package   imtfy
 * @author    haijun liu mail:875678704@qq.com
 * @version   1.1.1
 */
define('内存初始',memory_get_usage());
define('系统开始运行时间',microtime(true));
define('核心目录',dirname(__FILE__));
define('MTFY', '1.1.1');

sm('func');//导入核心函数文件
$mconfig=[];

$mconfig['Debug']		=false;
$mconfig['程序目录']	=dirname(dirname(__FILE__));
$mconfig['APP目录']		=$mconfig['程序目录'].DIRECTORY_SEPARATOR.'APP';
$mconfig['配置文件']	=$mconfig['APP目录'].DIRECTORY_SEPARATOR.'config.php';
$mconfig['路由文件']	=$mconfig['APP目录'].DIRECTORY_SEPARATOR.'router.php';
$mconfig['默认后缀']	='.html';

$mconfig['控制器目录']	=$mconfig['APP目录'].DIRECTORY_SEPARATOR.'controllers';
$mconfig['缓存目录']	=$mconfig['APP目录'].DIRECTORY_SEPARATOR.'cache';
$mconfig['模块目录']	=$mconfig['APP目录'].DIRECTORY_SEPARATOR.'models';

$mconfig['模板目录']	=$mconfig['APP目录'].DIRECTORY_SEPARATOR.'templates';
$mconfig['模板目录结构']='dir';//模板目录结构  dir:目录形式 index/index   file 文件形式  index_index

$mconfig['公共目录']	=$mconfig['程序目录'].DIRECTORY_SEPARATOR.'public';

$mconfig['第三方目录']	=$mconfig['程序目录'].DIRECTORY_SEPARATOR.'vendor';
$mconfig['换行']		=DIRECTORY_SEPARATOR;

if(@is_array($config)){
	$mconfig = array_merge($mconfig, $config);
	unset($config);
}
foreach($mconfig as $key =>$val){
	if(!defined($key))define($key,$val);
}
unset($key);
unset($val);
unset($mconfig);
header('content-type:text/html; charset=utf-8');
if(c('session','start')){startSession();}//初始化session
//导入第三方库
include_once 第三方目录.换行.'autoload.php';

//初始化路由
$router =@$router??(new router)->getrouter();
if(@$router['func']){
	$newrouter=[];
	try{$newrouter=@$router['func']($router);}catch(\Throwable $e){}
	if(is_array($newrouter))array_merge($router,$newrouter);
	unset($router['func']);
}
//判断程序目录
$router[0]=$router[0]??'index';
if(is_dir(控制器目录.DIRECTORY_SEPARATOR.$router[0].DIRECTORY_SEPARATOR)){
	define('M_PATH_DIR',控制器目录.DIRECTORY_SEPARATOR.$router[0]);
	define('M_PATH' , $router[0]);
	array_shift($router);
}else{
	define('M_PATH_DIR' ,控制器目录);
	define('M_PATH' , '');
};
//加载目录前置文件
if(is_file(M_PATH_DIR.DIRECTORY_SEPARATOR.'__init.php')){include M_PATH_DIR.DIRECTORY_SEPARATOR.'__init.php';}


$router[0]=@$router[0]??'index';
if(!preg_match('/^([a-z]|[A-Z]|[0-9])+$/Uis', $router[0])){$router[0] = 'index';}
$controllerFile = M_PATH_DIR.DIRECTORY_SEPARATOR.$router[0].'.php';
if(!is_file($controllerFile)){
	$router[0]='index';
	$controllerFile=M_PATH_DIR.DIRECTORY_SEPARATOR.'index.php';
}
define('M_C',$router[0]);

$router[1]=@$router[1]??'index';
if(!preg_match('/^([a-z]|[A-Z]|[0-9])+$/Uis', $router[1])){$router[1] = 'index';}
define('M_M',$router[1]);
//删除路由变量，转移到全局get数组
array_shift($router);
array_shift($router);
$GLOBALS['gets']=$router;unset($router);
//加载运行控制器方法
require $controllerFile;unset($controllerFile);
//实例化
$appClassName=M_C.'Con';
if(class_exists($appClassName)){
	$APP=new $appClassName();
}else{
	die('错误');//后期做页面
}
@call_user_func([$APP, '__init']);
@call_user_func([$APP, M_M]);
M_runLog();

function sm($m){
	$fileUri=核心目录.DIRECTORY_SEPARATOR.'models'.DIRECTORY_SEPARATOR.$m.'.php';
	if(is_file($fileUri))include_once $fileUri;
}
class router{
	public $router=[];
	public function __construct(){
		$path=获取URL();
		if(substr($path,0,1)!='/') {$path='/'.$path;}
		$noarguri=explode('?',$path);
		$GLOBALS['no_arg_uri']=$noarguri[0];
		@header(base64_decode('WC1Qb3dlcmVkLUJ5OmltdGZ5LmNvbQ=='));
		if(c('自定义路由')){
			$routes=配置信息(路由文件);
			if(!$routes){goto 默认路由;}
			if(is_object($routes))$routes=$routes();
		foreach($routes as $routerkey=>$routervalue) {
			if(\is_string($routervalue)){$routervalue=\json_decode($routervalue,1);}
			$ifmatch=true;
			
			if(isset($routervalue['domain'])) {$ifmatch=$this->macthdomain($routervalue['domain']);}
			
			if($ifmatch){
				if(!isset($routervalue['uri'])){continue;}
				if($this->matchuris($routervalue['uri'],$noarguri[0])===true) {
					//解析RES
					//res= [/APP目录]/控制器文件/函数
					if(substr($routervalue['res'],0,1)=='/') {$routervalue['res']=substr($routervalue['res'],1);}
					$this->router=explode('/',$routervalue['res']);
					$this->router['func']=@$routervalue['func'];	
					return;
				}
			}
		}
		//默认route;
		}
		默认路由:
		$dpath=$GLOBALS['no_arg_uri'];
		if(默认后缀){$dpath = str_replace(默认后缀, '', $dpath);}
		$res = explode('/', $dpath);
		if(empty($res[0])){array_shift($res);}
		$this->router=array_merge($res,$this->router);
	}
	function getrouter(){
		return $this->router;
	}
	//判断入口域名规则
	function macthdomain($domains) {
		if(!is_array($domains)) {
			if(empty($domains)) {Return true;}
			$domains=explode(';',strtolower($domains));
		}
		foreach($domains as $val) {
			$val=strtolower(trim($val));
			if($val==$this->servername()) {Return true;}
			if($val=='*') {Return true;}
			$thisstripos=stripos($val,'*');
			if($thisstripos===false) {}else {
				$topdomain=substr($val,$thisstripos+1,strlen($val)-$thisstripos);
				if(substr($this->servername(),-strlen($topdomain))==$topdomain) {Return true;}
				if('*.'.$this->servername()==$val)Return true;
			}
		}
		Return false;
	}
	
	function matchuris($uris,$uri) {
		if(!is_array($uris)) {
			$uris=explode(';',$uris);
		}
		foreach($uris as $val) {
			if(!empty($val)) {
				if(strpos($val,'?')===false) {
					$uri=$GLOBALS['no_arg_uri'];
				}
				if($this->matchuri($val,$uri)===true) {
					Return true;
				}
			}
		}
		Return false;
	}
	//路由匹配
	function matchuri($preguri,$uri) {
		$preguri=urlencode($preguri);
		$preguri=$this->uridecode($preguri);
		if($preguri==$uri && strpos($preguri,'(')===false && strpos($preguri,'[')===false && strpos($preguri,'{')===false) {
			Return true;
		}
		preg_match_all('/[{|\[|(](.*)[}|\]|)]/U',$preguri,$getarray);
		$newrouteruri=$preguri;
		if(count($getarray)>0) {
			foreach($getarray[0] as $getkey=>$getval) {
				if(substr($getval,0,1)=='{') {
					//$newrouteruri=str_replace($getval,'(.+)',$newrouteruri);((?!\/).+)
					$newrouteruri=str_replace($getval,'{{*}}',$newrouteruri);
				}
				if(substr($getval,0,1)=='(') {
					$newrouteruri=str_replace($getval,'([0-9]+)',$newrouteruri);
				}
				if(substr($getval,0,1)=='[') {
					$newrouteruri=str_replace($getval,'([a-zA-Z0-9_]+)',$newrouteruri);
				}
			}
			$newrouteruri=str_replace('/',"\\/",$newrouteruri);
			$newrouteruri=str_replace('?',"\?",$newrouteruri);
			$newrouteruri=str_replace('{{*}}',"((?!\/).+)",$newrouteruri);
			preg_match_all('/'.'startofuri-'.$newrouteruri.'-endofuri'.'/','startofuri-'.$uri.'-endofuri',$ifmatch);
			if(isset($ifmatch[1][0])) {
				foreach($getarray[1] as $getkey=>$getval) {
					$_GET[$getval]=urldecode($ifmatch[1+$getkey][0]);
				}
				Return true;
			}else {
				Return false;
			}
		}else {
			Return false;
		}
	}
	function uridecode($uri) {
		$uri=str_replace('%28','(',$uri);
		$uri=str_replace('%29',')',$uri);
		$uri=str_replace('%7B','{',$uri);
		$uri=str_replace('%7D','}',$uri);
		$uri=str_replace('%5B','[',$uri);
		$uri=str_replace('%5D',']',$uri);
		$uri=str_replace('%2F','/',$uri);
		$uri=str_replace('%3F','?',$uri);
		$uri=str_replace('%3D','=',$uri);
		$uri=str_replace('%26','&',$uri);
		$uri=str_replace('+','%20',$uri);
		$uri=str_replace('%25','%',$uri);
		Return $uri;
	}
	//域名整理
	function servername() {
		if(!isset($_SERVER['S_NAME'])) {
			if(isset($_SERVER['HTTP_HOST'])){
				$thisserver_names=explode(':',$_SERVER['HTTP_HOST']);
				$_SERVER['S_NAME']=$thisserver_names[0];
			}else {
				$_SERVER['S_NAME']=$_SERVER['SERVER_NAME'];
			}
			$_SERVER['S_NAME']=strtolower($_SERVER['S_NAME']);
		}
		Return $_SERVER['S_NAME'];
	}
}